package com.xuan.juc.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*
* 用lock解决k++
* */
public class CasDemo2 {
    //public volatile static AtomicInteger k = new AtomicInteger();

    public volatile static int k;

    public static void sum(){

        for (int i = 0; i < 10000; i++) {
            k++;
        }

    }


    public static void main(String[] args) throws InterruptedException {

        Lock lock = new ReentrantLock();
        Thread t1 = new Thread(()->{

            lock.lock();
            try {
                sum();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

        });
        Thread t2 = new Thread(()->{
            lock.lock();
            try {
                sum();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();
        System.out.println(k);


    }



}
